package com.example.demo.jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Rocket
 * @version 10.0.1
 * @date 2021-08-15 2:30 PM
 */
@WebServlet(name="jdbc delete", urlPatterns = {"/delete"})
public class JDBCDelete extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Connection conn = null;
        String id = req.getParameter("id");
        if(id == null) {
            throw new ServletException("Id is null");
        }
        try {
            Class.forName("org.h2.Driver");
            conn = DriverManager.getConnection("jdbc:h2:C:/study/db/h2/bin/test;AUTO_SERVER=TRUE;AUTO_RECONNECT=TRUE", "sa", "123");
            resp.getWriter().println(conn);
            PreparedStatement stmt = conn.prepareStatement("delete from test where id= ?");

            stmt.setInt(1, Integer.parseInt(id));
            int count = stmt.executeUpdate();
            if(count > 0 ) {
                resp.getWriter().println("delete successfully");
            } else {
                resp.getWriter().println("failed to delete");
            }


        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return;
        } finally {
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                }
            }
        }


    }
}
